package com.loong.x.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loong.x.app.entity.User;
import com.loong.x.app.service.UserService;
import com.loong.x.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Description
 *
 * @author wcloong
 * @version 0.1.0
 * @since 2023/8/1 13:55
 */
@Slf4j
//做json处理
@RestController
//@Controller --- 返回视图
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //使用 HttpServletRequest 对象获取 HTTP 请求相关的信息，如：客户端 IP、HTTP Header 中的属性等
    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user) {
        // 页面提交的密码md5加密
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        // 根据前端输入的用户名查询数据库
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 等值查询
        userLambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        // 查询到的结果usr
        User usr = userService.getOne(userLambdaQueryWrapper);
        // 没有查询到
        if (usr == null) {
            return R.error("登录失败");
        }
        // 密码比对不成功
        if (!usr.getPassword().equals(password)) {
            System.out.println(password);
            return R.error("密码不正确");
        }
        // 查看用户状态 是否禁用 0为禁用 1正常
        if (usr.getStatus() == 0) {
            return R.error("账号已禁用");
        }
        // 登录成功,将用户id存入Session并返回登录成功结果
//        request.getSession().setAttribute("token", usr.getId());
        System.out.println(R.success(usr));
        return R.success(usr);
    }

    @GetMapping("/info")
    public R<User> getUserInfo(@RequestParam("token") String token) {
        System.out.println("get-info-token:" + token);
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 等值查询
        userLambdaQueryWrapper.eq(User::getId, token);
        User user = userService.getById(token);
//        System.out.println("用户信息：" + user);
        return R.success(user);
    }

    @PostMapping("/logout")
    public R<User> logout(@RequestHeader("X-Token") String token) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 等值查询
        userLambdaQueryWrapper.eq(User::getId, token);
        User user = userService.getById(token);
        return R.success(user);
    }

    //    public R<List<User>> getUsers(@RequestParam(value = "searchData", required = false) User user) {
//    public R<List<User>> getUsers(@RequestParam Map<String,Object> user) {
    @GetMapping("/list")
    public R<List<User>> getUsers(@RequestParam String roles, @RequestParam String keyword) {
        System.out.println("用户： " + roles + "-关键字" + keyword);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        // 判断username的长度（非空）并且username == username
//        wrapper.eq(StringUtils.hasLength(user.getUsername()), User::getUsername, user.getUsername());
//        wrapper.eq(StringUtils.hasLength(user.getName()), User::getName, user.getName());
//        wrapper.eq(StringUtils.hasLength(user.getPhone()), User::getPhone, user.getPhone());
        wrapper.eq(StringUtils.hasLength(roles), User::getRoles, roles);

//        wrapper.eq(StringUtils.hasLength(username), User::getUsername, username);
//        wrapper.eq(StringUtils.hasLength(roles), User::getRoles, roles)
//                .eq(StringUtils.hasLength(roles), User::getRoles, roles);

        wrapper.and(c -> c.like(User::getName, keyword)
                .or().like(User::getUsername, keyword)
                .or().like(User::getPhone, keyword));

//        System.out.println(wrapper.getSqlSelect());

        List<User> users = userService.list(wrapper);

        return R.success(users);
    }


    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String roles, String keyword) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, keyword);

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件

        queryWrapper.eq(StringUtils.hasLength(roles), User::getRoles, roles);

        if (StringUtils.hasLength(keyword)) {
            queryWrapper.and(c -> c.like(User::getName, keyword)
                    .or().like(User::getUsername, keyword)
                    .or().like(User::getPhone, keyword));
        }

        //添加排序条件
        queryWrapper.orderByDesc(User::getUpdateTime);

        //执行查询
        userService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }


    @PostMapping("/add")
    public R<String> addUser(HttpServletRequest request, @RequestBody User user) {
        log.info("新增员工：{}", user);
        user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        userService.save(user);
        return R.success("新增员工成功");
    }

    @PutMapping
    public R<String> update(@RequestBody User user) {
        String password = user.getPassword();
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userService.updateById(user);
        return R.success("修改成功！");
    }

    @DeleteMapping
    public R<String> delete(@RequestBody User user) {
        userService.removeById(user);
        return R.success("删除成功！");
    }
}


